package com.itheima.filter;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;

import java.io.IOException;
@Slf4j
@WebFilter("/*")
public class TokenFilter implements Filter {
//
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String path = req.getRequestURI();
        log.info("请求路径：{}",path);
        if(path.endsWith("/login"))
        {
            chain.doFilter(servletRequest,servletResponse);
            return;
        }
        String token = req.getHeader("Token");
        log.info("请求头中的令牌：{}",token);
        if(StringUtils.hasText(token))
        {
            try {
                Claims claims = JwtUtils.parseJWT(token);
                log.info("token内容：{}",claims);
                //获取登录用户的id
                Integer userId = claims.get("id", Integer.class);
                //存入当前线程中
                CurrentHolder.setCurrentId(userId);
                chain.doFilter(servletRequest,servletResponse);
                return;
            } catch (Exception e) {
                log.error("解析令牌失败", e);
            }finally {
                //移除当前线程，防止内存泄漏
                CurrentHolder.remove();
            }
        }
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        res.setStatus(HttpStatus.UNAUTHORIZED.value());//401
    }
}

